<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Xiaohuan Chat</title>
    <link rel="icon" type="shortcut icon" href="/img/favicon.png">
    <link rel="stylesheet" href="/css/chat.css">
    <link rel="stylesheet" href="/layui/css/layui.css">
    <!-- 动画精灵的配置-->
    <script src="https://l2dwidget.js.org/lib/L2Dwidget.min.js"></script>
    <script type="text/javascript">
        //角色数组
        var characters = ['chitose','Epsilon2.1','Gantzert_Felixander','haru01','haru02','haruto','hibiki','hijiki','izumi','koharu','miku','nico','ni-j','nipsilon','nito','shizuku','tororo','tsumiki','Unitychan','wanko','z16'];

        //随意选择其中一个
        var petName = characters[16];
        L2Dwidget.init({
            "model": {
                "jsonPath": "https://unpkg.com/live2d-widget-model-" + petName + "@1.0.5/assets/" + petName + ".model.json",
                "scale": 1
            },
            "display": {
                "position": "right",
                "width": 150,
                "height": 300,
                "hOffset": 0,
                "vOffset": -20
            },
            "mobile": {
                "show": true,
                "scale": 0.5
            },
            "react": {
                "opacityDefault": 0.8,
                "opacityOnHover": 1
            },
            "dialog": {
                "enable": true,
                "script": {
                    //每隔20s显示的句子
                    'every idle 20s': '$hitokoto$',
                    //悬浮在down类型标签显示的对话框
                    'hover .sendto': '给你的好朋友发送消息哟，喵咪',
                    'hover .tit': '欢迎来到Cfeng.net, 玩的愉快哦*o*',
                    //触碰身体显示
                    'tap body': '哎呀！别碰我！',
                    //触碰脸显示
                    'tap face': '讨厌，快学习',
                }
            }
        });
    </script>
    <style>
        #exitChat {
            color: #c6d6ff;
            float: right;
        }

        #exitChat:hover {
            color: #8B0000;
        }
    </style>
</head>
<body background="/img/indexbg0.jpg">
<div class="main">
    <div class="top">
        <div class="top-left">
<!--            <div class="header"></div>-->
            <a href="/sys/toUser"><img th:src="@{${chatUser.userHeaderImg}}" alt="" class="header" /></a>
            <div class="search">
                <input type="text">
                <i class="icon-sear"></i>
            </div>
        </div>
        <div class="top-type">
            <a href="#" class="news icon-site"></a>
            <a href="#" class="friend icon-site"></a>
            <a href="#" class="file icon-site"></a>
        </div>
        <div class="top-right">
<!--            <i class="ic-menu ic-same"></i>-->
<!--            <i class="ic-shrink ic-same"></i>-->
<!--            <i class="ic-boost ic-same"></i>-->
<!--            <i class="ic-close ic-same"></i>-->
            <a href="javascript:void(0)" id="fullScreen" title="全屏"><i class="layui-icon layui-icon-screen-full"></i></a>
            <a id="exitChat" href="javascript:void(0)">退出聊天室</a>
        </div>
    </div>
    <div class="box">
        <!-- 聊天列表-->
        <div class="chat-list">
            <div class="list-box select">
                <img class="chat-head" src="/1111111111111111.jpg" alt="">
                <div class="chat-rig">
                    <p class="title">世界频道</p>
                    <p id="latestWordMessage" class="text">欢迎加入聊天室</p>
                </div>
            </div>
            <!-- select 为选中样式 -->
        </div>
        <!-- 聊天信息显示界面 -->
        <div class="box-right">
            <div  class="recvfrom">
                <div class="nav-top">
                    <p id="channelName">世界频道</p>
                </div>
                <div id="chatMessageContainer" class="news-top">
                    <ul id="WorldWideMessage">
                        <li class="other">
                            <div class="avatar"><img src="/img/background.jpg" alt=""></div>
                            <div class="msg">
                                <p  class="msg-name">管理员</p>
                                <p class="msg-text">欢迎大家加入聊天室, 尽情Chat <emoji class="pizza"></emoji></p>
                                <time>20:18</time>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="sendto">
                <div class="but-nav">
                    <ul>
                        <li class="font"></li>
                        <li class="face"></li>
                        <li class="cut"></li>
                        <li class="page"></li>
                        <li class="old"></li>
                    </ul>
                </div>
                <div class="but-text">
                    <textarea name="" id="messageToSave" cols="110" rows="6"></textarea>
                    <a  href="javascript:void(0)" class="button" onclick="sendMessage()">发送</a>
                </div>
            </div>
        </div>

    </div>


</div>

<script src="/js/JQuerym.js"></script>
<!-- 引入socket.JS, 为了直接在Http协议中模拟Ws协议，如果直接使用ws协议，不需要socketJS-->
<script src="/js/socketjs.js"></script>
<!-- 引入stomp.js  操作STOMP客户端-->
<script src="/js/stomp.js"></script>

<script type="text/javascript">
    var username = '';
    var receiver = '';
    var socketJS = null;
    var stompClient = null;
    //加载的完成就会发起连接
    $(function () {
        username = "[[${chatUser.userName}]]";
        console.log(username);
        socketJS = new SockJS('/ws');
        stompClient = Stomp.over(socketJS);
        stompClient.connect({},onConnected,onError);
    })

    onConnected = function () {
        console.log("连接成功");
        //订阅公共频道
        stompClient.subscribe("/topic/public",onMessageReceived);
        //订阅历史记录
        stompClient.subscribe("/app/chat.lastTenMessage",onHistoryMessageReceived)
        //订阅私聊主题
        var url = "/user/" + username + "/chat";
        console.log(url);
        stompClient.subscribe(url,onPrivateMessageReceived);
        //发送上线信息给服务器
        stompClient.send("/app/chat.addUser",{},JSON.stringify({sender: username,type: 'JOIN'}));
    }

    onError = function () {
        console.log("连接失败")
    }

    //断开连接,返回首页
    $("#exitChat").click(function () {
        socketJS.close(); //断开连接
        location.href = "/sys/toIndex";
    })

    //发送消息
    //发送消息到服务端处理转发
    sendMessage = function () {
        var messageContent = $("#messageToSave").val().trim();
        if(username == '' || username == null) {
            alert("出现异常，用户名为空");
        }
        //消息和连接
        if(messageContent && stompClient) {
            var chatMessage = {
                sender: username,
                content: messageContent,
                receiver: receiver,
                type: 'CHAT'
            };
            stompClient.send("/app/chat.sendMessage",{},JSON.stringify(chatMessage));
            $("#messageToSave").get(0).value = '';
        }
    }

    //接收世界频道聊天消息并放入聊天列表
    onMessageReceived = function(payload) {
        var message =JSON.parse(payload.body); //转为JSON对象

        if(message.type == 'JOIN') {
            var msg = "<li style='text-align: center;color: #bbbbd1;'>系统消息: ";
            msg += username;
            msg += "加入！</li>";
            $("#WorldWideMessage").append(msg);
        } else if(message.type == 'LEAVE') {
            var msg = "<li style='text-align: center;color: #bbbbd1;'>系统消息";
            msg += username;
            msg += "离开！</li>";
            $("#WorldWideMessage").append(msg);
        } else {
            //增加子标签即可
            if(username == message.sender) {
                var msg = "<li class='self'><div class='avatar'><img src=/"+ message.senderHeadImg + " alt=''></div><div class='msg'><p class='msg-name'>" + message.sender;
                msg += "</p><p class='msg-text'>" + message.content;
                var time = new Date();
                msg += "<emoji class='pizza'></emoji></p><time>" + time.getFullYear() + "-" + dateFormat((time.getMonth() + 1)) + "-" + time.getDate() + " " + dateFormat(time.getHours()) + ":" + dateFormat(time.getMinutes());
                msg += "</time></div></li>";
                //self样式
                $("#WorldWideMessage").append(msg);
            }else {
                var msg = "<li class='other'><div class='avatar'><img src=/" + message.senderHeadImg + " alt=''></div><div class='msg'><a onclick='convertUser($(this))' href='javascript:void(0)'><p class='msg-name'>" + message.sender;
                msg += "</p></a><p class='msg-text'>" + message.content;
                var time = new Date();
                msg += "<emoji class='pizza'></emoji></p><time>" + time.getFullYear() + "-" + dateFormat((time.getMonth() + 1)) + "-" + time.getDate() + " " + dateFormat(time.getHours()) + ":" + dateFormat(time.getMinutes());
                msg += "</time></div></li>";
                $("#WorldWideMessage").append(msg);
            }
            //同时将消息显示在频道下方
            $("#latestWordMessage").text(message.sender + ":" + message.content);
        }
    }

    //历史记录消息处理，主要是将数组拆开，调用Message
    onHistoryMessageReceived = function(messageList) {
        var msgString = 'IM' +  messageList
        var messages = JSON.parse(msgString.slice(msgString.indexOf('[')));
        for(i = 0; i < messages.length; i ++) {
            var message = messages[i];
            if(username == message.sender) {
                var msg = "<li class='self'><div class='avatar'><img src=/"+ message.senderHeadImg + " alt=''></div><div class='msg'><p class='msg-name'>" + message.sender;
                msg += "</p><p class='msg-text'>" + message.content;
                var ltime = message.createTime;
                var time = "" + ltime;
                msg += "<emoji class='pizza'></emoji></p><time>" + time.replace("T"," ").substring(0,16);
                msg += "</time></div></li>";
                //self样式
                $("#WorldWideMessage").append(msg);
            }else {
                var msg = "<li class='other'><div class='avatar'><img src=/" + message.senderHeadImg + " alt=''></div><div class='msg'><a onclick='convertUser($(this))' href='javascript:void(0)'><p class='msg-name'>" + message.sender;
                msg += "</p></a><p class='msg-text'>" + message.content;
                var ltime = message.createTime;
                var time = "" + ltime;
                msg += "<emoji class='pizza'></emoji></p><time>" + time.replace("T"," ").substring(0,16);
                msg += "</time></div></li>";
                $("#WorldWideMessage").append(msg);
            }
            //同时将消息显示在频道下方
            $("#latestWordMessage").text(message.sender + ":" + message.content);
        }
    }



    dateFormat = function (number) {
        if(number >= 10) return number;
        return '0' + number;
    }

    //私聊
    convertUser = function ($this) {
        var $parent= $this.parent(".msg");
        var imgSrc = $parent.prev(".avatar").children("img").get(0).src;
        receiver =  $this.children("p:first-child").text();
        $("#channelName").text(receiver);
        console.log(imgSrc);
        var listBoxappend = "<div class='list-box select'><img class='chat-head' src=' " + imgSrc;
        listBoxappend += "' alt=''><div class='chat-rig'><p class='title'>" + receiver;
        listBoxappend += "</p><p class='text'>";
        listBoxappend += "</p></div></div>";
        $(".chat-list").append(listBoxappend);

        $("#WorldWideMessage").css("display","none");
        // $(".sendto").before($("<div id='" + receiver +"channel' class='recvfrom'><div class='nav-top'><p>" + receiver + "</p></div><div class='news-top'><ul id='chatMessage'></li></ul></div></div></div>"));
        //追加对应的user的ul
        $("#chatMessageContainer").append("<ul id='Message'" + receiver + "></ul>");
    }

    onPrivateMessageReceived = function (payload) {
        console.log(payload);
        var message = JSON.parse(payload.body);
        console.log("进入了私聊方法");
        if (username == message.sender) {
            var msg = "<li class='self'><div class='avatar'><img src=/" + message.senderHeadImg + " alt=''></div><div class='msg'><p class='msg-name'>" + message.sender;
            msg += "</p><p class='msg-text'>" + message.content;
            var time = new Date();
            msg += "<emoji class='pizza'></emoji></p><time>" + dateFormat(time.getHours()) + ":" + dateFormat(time.getMinutes());
            msg += "</time></div></li>";
            //self样式
            $("#chatMessageContainer").children("ul:last").append(msg);
        } else {
            var msg = "<li class='other'><div class='avatar'><img src=/" + message.senderHeadImg + " alt=''></div><div class='msg'><a onclick='convertUser($(this))' href='javascript:void(0)'><p class='msg-name'>" + message.sender;
            msg += "</p></a><p class='msg-text'>" + message.content;
            var time = new Date();
            msg += "<emoji class='pizza'></emoji></p><time>" + dateFormat(time.getHours()) + ":" + dateFormat(time.getMinutes());
            msg += "</time></div></li>";
            $("#chatMessageContainer").children("ul:last").append(msg);
        }
        //同时将消息显示在频道下方
        $(".chat-list").children("div:last").children(".text").text(message.sender + ":" + message.content);
    }

    // layui的全屏
    //全屏
    $('#fullScreen').click(function () {
        var v = "layui-icon-screen-full", p = "layui-icon-screen-restore";
        var n = $(this).find("i");
        var s = document.fullscreenElement || document.msFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || false;
        if (s) {
            var r = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen;
            if (r) {
                r.call(document)
            } else {
                if (window.ActiveXObject) {
                    var u = new ActiveXObject("WScript.Shell");
                    u && u.SendKeys("{F11}")
                }
            }
            n.addClass(v).removeClass(p)
        } else {
            var o = document.documentElement;
            var q = o.requestFullscreen || o.webkitRequestFullscreen || o.mozRequestFullScreen || o.msRequestFullscreen;
            if (q) {
                q.call(o)
            } else {
                if (window.ActiveXObject) {
                    var u = new ActiveXObject("WScript.Shell");
                    u && u.SendKeys("{F11}")
                }
            }
            n.addClass(p).removeClass(v)
        }
    });
</script>
</body>
</html>